<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="产品名称">
          <el-input
            v-model="searchParam.materialName"
            placeholder="请输入产品名称"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="产品编号">
          <el-input
            v-model="searchParam.materialCode"
            placeholder="请输入产品编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="primary" @click="coreBasicImport">导入 </el-button>
        <el-button
          @click="
            useDownload(
              '/mes/mescorebasicdata/exportTemp',
              '制芯基础数据上传模板',
              searchParam
            )
          "
        >
          导入模板下载
        </el-button>
        <el-button
          class="ml-3"
          @click="
            useDownload(
              '/mes/mescorebasicdata/export',
              '制芯基础数据',
              searchParam
            )
          "
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="index"
          label="序号"
          width="70"
          key="id"
          align="center"
        />

        <template v-for="item in tableColumns" :key="item">
          <TableColumn v-if="item.prop && item.isShow" :column="item">
            <template v-for="slot in Object.keys($slots)" #[slot]="scope">
              <slot :name="slot" v-bind="scope"></slot>
            </template>
          </TableColumn>
        </template>
        <!-- <el-table-column
          label="产品名称"
          prop="materialName"
          min-width="150"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.materialName }}
          </template>
        </el-table-column>
        <el-table-column
          label="砂芯编号"
          prop="sandCoreNumber"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="件/M"
          prop="pm"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="M/S"
          prop="ms"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="计划停机"
          prop="scheduledOutage"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="设备停机"
          prop="equipmentShutdown"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="班制"
          prop="shiftSet"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="班产"
          prop="tactYield"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="冷芯/热芯"
          prop="coreState"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="设备型号"
          prop="equipModel"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="砂型号"
          prop="sandModel"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column
          label="需求人数"
          prop="demandPeople"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        /> -->
        <!--<el-table-column
          label="备注"
          prop="remarks"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="创建人名"
          prop="createdUserName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="更新时间"
          prop="lastUpdateTime"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="更新人名"
          prop="lastUpdatedUserName"
          min-width="100"
          show-overflow-tooltip
        />-->
        <el-table-column fixed="right" label="操作" width="180" align="center">
          <template #default="scope">
            <!--<el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button>-->
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="deleteItem(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <mescorebasicdata-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
    <!--导入-->
    <ImportExcel ref="coreBasicImportRef" />

    <!-- 列设置 -->
    <ColSetting
      v-model:col-setting="tableColumns"
      v-model:search-setting="searchColumns"
      @search-handle="(e:boolean) => (showSearch = e)"
    />
  </div>
</template>

<script setup lang="tsx">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";

defineOptions({
  name: "MESMESCOREBASICDATA",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/mes/mescorebasicdata/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  materialCode: "",
  materialName: "",
};

const deleteParam = {
  api: "/mes/mescorebasicdata/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/mes/mescorebasicdata/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开制芯基础数据表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改制芯基础数据";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增制芯基础数据";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开制芯基础数据表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "制芯基础数据详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

// 导入excel
const uploadApi = "/mes/mescorebasicdata/upload";
const excelBox = ref(false);
const uploadBtn = ref(false);
const uploadFile = ref("");
const fileName = ref("");

function excelBoxOpen() {
  excelBox.value = true;
}

function getfilepath(e: any) {
  const file = e.target.files[0];
  fileName.value = file.name;
  uploadFile.value = file;
  uploadBtn.value = false;
}

function upload() {
  if (!uploadFile.value) {
    ElMessage({
      type: "warning",
      message: "请选择文件！",
    });
    return;
  }

  let formdata = new FormData();
  formdata.append("file", uploadFile.value);
  let config = { headers: { "Content-Type": "multipart/form-data" } };
  request
    .post(uploadApi, formdata, config)
    .then((res) => {
      ElMessage({
        type: "success",
        message: "上传成功！",
      });

      excelBox.value = false;
      uploadBtn.value = true;
      search();
    })
    .catch((error) => {
      console.log(error);
    });
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/mes/mescorebasicdata/deleteItem/${id}`,
      method: "post",
    }).then((res) => {
      ElMessage.success("删除成功！");
      search();
    });
  });
}
// 导入计划
const coreBasicImportRef = ref();
async function coreBasicImportApiFunc(formdata: FormData, config: any) {
  await request
    .post(uploadApi, formdata, config)
    .then((res: any) => {
      coreBasicImportRef.value.resCode = 0;
      if (res.code === 200) {
        ElMessage({
          type: "success",
          message: "上传成功！",
        });
      }
    })
    .catch((e) => {
      coreBasicImportRef.value.resCode = 500;
    });
}
const coreBasicImport = () => {
  let params = {
    title: "导入制芯基础数据",
    tempApi: "", //模板下载
    importApi: coreBasicImportApiFunc, // 导入
    getTableList: getTableList, // 成功后回调
    isShowTemp: false,
    otherParams: {},
  };
  coreBasicImportRef.value.acceptParams(params);
};

const tableColumns = reactive([
  {
    prop: "materialName",
    label: "产品名称",
    minWidth: 150,
    isShow: true,
    align: "left",
  },
  {
    prop: "sandCoreNumber",
    label: "砂芯编号",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "pm",
    label: "件/M",
    minWidth: 100,
    isShow: true,
    align: "right",
    headerAlign: "center",
  },
  {
    prop: "ms",
    label: "M/S",
    minWidth: 100,
    isShow: true,
    align: "right",
    headerAlign: "center",
  },
  {
    prop: "scheduledOutage",
    label: "计划停机",
    minWidth: 100,
    isShow: true,
    align: "right",
    headerAlign: "center",
  },
  {
    prop: "equipmentShutdown",
    label: "设备停机",
    minWidth: 100,
    isShow: true,
    align: "right",
    headerAlign: "center",
  },
  {
    prop: "shiftSet",
    label: "班制",
    minWidth: 100,
    isShow: true,
    align: "right",
    headerAlign: "center",
  },
  {
    prop: "tactYield",
    label: "班产",
    minWidth: 100,
    isShow: true,
    align: "right",
    headerAlign: "center",
  },
  {
    prop: "coreState",
    label: "冷芯/热芯",
    minWidth: 100,
    isShow: true,
    align: "center",
  },
  {
    prop: "equipModel",
    label: "设备型号",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "sandModel",
    label: "砂型号",
    minWidth: 200,
    isShow: true,
    align: "left",
  },
  {
    prop: "demandPeople",
    label: "需求人数",
    minWidth: 100,
    isShow: true,
    align: "right",
    headerAlign: "center",
  },
]);

//  render: (scope: any) =>
//       scope.row.repairLevel == "1" && scope.row.repairLevel * 1 < 4 ? (
//         <el-tag type="danger">
//           {useDictionary("EamFaultLevel", scope.row.repairLevel)}
//         </el-tag>
//       ) : scope.row.repairStatus * 1 >= 4 ? (
//         <el-tag type="info" type="success">
//           {useDictionary("EamFaultLevel", scope.row.repairLevel)}
//         </el-tag>
//       ) : scope.row.repairLevel !== "1" && scope.row.repairStatus * 1 < 4 ? (
//         <el-tag>{useDictionary("EamFaultLevel", scope.row.repairLevel)}</el-tag>
//       ) : (
//         <div></div>
//       ),
const searchColumns = ref([]);
</script>
